<?php
namespace App\Repositories;
use Image;
use App\Project;
use Illuminate\Support\Facades\Storage;
class  ProjectsRepository
{
    public function create($request){
        $request->user()->projects()->create([
            'name'=>$request->name,
            'thumb'=>$this->thumbil($request),
        ]);
    }
    public function list(){
       return  $projects=request()->user()->projects()->get();
    }
    public function find($id){
     return Project::findOrfail($id);
    }
    public function update($request, $id){
        $project=$this->find($id);
        $project->name = $request->name;
        if ($request->hasFile('thumb')) {
            $this->exitsimg($project->thumb);
            $project->thumb=$this->thumbil($request);
        }
        $project->save();
    }
    public function thumbil($request){
        if ($request->hasFile('thumb')) {
            $thumb=$request->thumb;
            $name=$thumb->hashName();
            $thumb->storeAs('/public/thumb/original',$name);
            $path=storage_path('app/public/thumb/cropped/'.$name);
            Image::make($thumb)->resize(200,90)->save($path);
            return $name;
            
            
        }
       
    }
    public function todos($project){
        return $todos=$project->task()->where('completion',0)->get();
    }
    public function done($project){
        return $done=$project->task()->where('completion',1)->get();
    }
    public function delete($id){
        $project=$this->find($id);
        $this->exitsimg($project->thumb);
        $project->delete();
    }
    // 检查文件是否存在
    public function exitsimg($img){
        $path='public/thumb/original/'.$img;
        $exists = Storage::disk('local')->exists($path);
        if ($exists) {
            $this->delimg($path);
        }
    }
    // 删除图片
    public function delimg($path){
        $result=Storage::delete($path);
        if ($result) {
            return true;
        }else {
            return false;
        }
    }
}
